/* eslint-disable no-script-url */
/* eslint-disable eqeqeq */

import React, { PureComponent } from 'react';
import moment from 'moment';
import router from 'umi/router';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form, Icon as LegacyIcon } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Row,
  Col,
  Button,
  Select,
  Input,
  message,
  Modal,
  Menu,
  Dropdown,
  Divider,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import StandardTable from '@/components/StandardTable';
import styles from '@/utils/utils.less';
import { checkPermissions } from '@/utils/authority';
import HOCSelect from '@/components/AntDesign/Select';

// 引入头部组件
const { Option } = Select;
const { confirm } = Modal;
const FormItem = Form.Item;

@connect(({ guideprotect, loading }) => ({
  guideprotect,
  loading: loading.models.guideprotect,
}))
@Form.create()
class BasicList extends PureComponent {
  state = {
    del: 'delete', // 图标
    delDis: false, // 可用否
    selectedKeys: [],
    selectedRows: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.getList();
    dispatch({
      type: 'guideprotect/queryDictItemsByCodes',
      payload: ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE'],
    });
  }

  initSelect = () => {
    const {
      guideprotect: {
        pageData: { pagination },
      },
    } = this.props;
    this.getList(pagination.current, pagination.pageSize);
  };

  // 录入数据
  insertOne = () => {
    router.push('/searchmanage/guideprotect/insert');
  };

  getList = (current = 1, pageSize = 10, isClear = true) => {
    const { form, dispatch } = this.props;
    if (isClear) {
      this.setState({
        selectedKeys: [],
        selectedRows: [],
      });
    }
    form.validateFieldsAndScroll(['type', 'areaName'], (err, values) => {
      if (err) return;
      dispatch({
        type: 'guideprotect/updateModelData',
        payload: {
          formFieldsValue: values,
        },
      });
      const tempValues = {};
      Object.keys(values).forEach(key => {
        tempValues[key] = values[key] === undefined ? null : values[key].trim();
      });
      const params = {
        plcyInfoVo: {
          ...tempValues,
          type: tempValues.type && tempValues.type != '1' ? tempValues.type : undefined,
        },
        pageArg: {
          currentPage: current,
          pageSize,
        },
      };
      dispatch({
        type: 'guideprotect/fetchList',
        payload: params,
      });
    });
  };

  // 删除
  deleteMany = () => {
    const { selectedRows } = this.state;
    const inParam = {};
    const tmpArr = [];
    const {
      guideprotect: {
        pageData: { pagination },
      },
      dispatch,
    } = this.props;
    if (selectedRows.length === 0) {
      message.warning('请选择一条数据才能删除！');
      return;
    }
    confirm({
      title: '提示',
      content: '确定进行删除操作吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        selectedRows.forEach(value => {
          tmpArr.push({ plcyId: value.plcyId, vno: value.vno });
        });
        inParam.list = tmpArr;
        dispatch({
          type: 'guideprotect/deleteMany',
          payload: inParam,
        }).then(res => {
          if (res.success) {
            message.success('操作成功!');
            this.getList(pagination.current, pagination.pageSize);
          } else {
            message.warning(res.message || '服务端错误');
          }
        });
      },
      onCancel() {},
    });
  };

  // 查看详情
  goDetail = value => {
    router.push(`/searchmanage/guideprotect/detail?id=${value}`);
  };

  modify = value => {
    router.push(`/searchmanage/guideprotect/Modify?id=${value}`);
  };

  switchRun = (plcyId, vno, state) => {
    const {
      guideprotect: {
        pageData: { pagination },
      },
      dispatch,
    } = this.props;
    dispatch({
      type: 'guideprotect/switchRun',
      payload: {
        plcyId,
        vno,
        state,
      },
    }).then(res => {
      if (res.success) {
        message.success('操作成功！');
        this.getList(pagination.current, pagination.pageSize);
      } else {
        message.warning(res.message || '服务端错误');
      }
    });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, false);
  };

  handleSelectRows = (selectedRows, selectedKeys) => {
    this.setState({ selectedRows, selectedKeys });
  };

  render() {
    const {
      guideprotect: { policyData, pageData },
      loading,
      form: { getFieldDecorator },
    } = this.props;
    const { selectedKeys, selectedRows, delDis, del } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const columns = [
      {
        title: '政策标题',
        dataIndex: 'tit',
        key: 'tit',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '状态',
        align: 'center',
        dataIndex: 'state',
        key: 'state',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: text => {
          const statuCode = text == '1' ? '已启用' : '已禁用';
          return <span>{statuCode}</span>;
        },
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        key: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作时间',
        align: 'center',
        dataIndex: 'publishTime',
        key: 'publishTime',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: text => <span>{text ? moment(text).format('YYYY-MM-DD') : '--'}</span>,
      },
      {
        title: '操作',
        align: 'center',
        width: 200,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a href="javascript:;" onClick={() => this.goDetail(record.plcyId)}>
              查看
            </a>
            <Divider type="vertical" />
            <Dropdown
              overlay={
                record.state == '1' ? (
                  <Menu>
                    {checkPermissions('os:plcyInfo:updatePlcyState') && (
                      <Menu.Item
                        key="disabled"
                        onClick={() => this.switchRun(record.plcyId, record.vno, record.state)}
                      >
                        禁用
                      </Menu.Item>
                    )}
                    {checkPermissions('os:plcyInfo:update') && (
                      <Menu.Item key="edit" onClick={() => this.modify(record.plcyId)}>
                        修改
                      </Menu.Item>
                    )}
                  </Menu>
                ) : (
                  <Menu>
                    {checkPermissions('os:plcyInfo:updatePlcyState') && (
                      <Menu.Item
                        key="enable"
                        onClick={() => this.switchRun(record.plcyId, record.vno)}
                      >
                        启用
                      </Menu.Item>
                    )}
                    {checkPermissions('os:plcyInfo:update') && (
                      <Menu.Item key="edit" onClick={() => this.modify(record.plcyId)}>
                        修改
                      </Menu.Item>
                    )}
                  </Menu>
                )
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];

    const tempPolicyData = [{ itemCode: '1', itemName: '全部' }].concat(policyData);
    return (
      <div>
        <PageHeaderWrapper>
          <Card className={styles.searchCard}>
            <div className={styles.tableListForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem {...formItemLayout} label="政策类型">
                      {getFieldDecorator('type', {
                        rules: [{ required: false }],
                      })(
                        <HOCSelect
                          placeholder="请选择"
                          style={{ width: '100%' }}
                          allowClear
                          optionFilterProp="children"
                          showSearch
                        >
                          {tempPolicyData.map(value => (
                            <Option key={value.itemCode} value={value.itemCode}>
                              {value.itemName}
                            </Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem {...formItemLayout} label="政策地区">
                      {getFieldDecorator('areaName', {
                        rules: [{ required: false }],
                      })(<Input placeholder="请输入政策地区" style={{ width: '100%' }} />)}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <Button
                      type="primary"
                      style={{ marginLeft: 20 }}
                      onClick={() => this.getList()}
                    >
                      查询
                    </Button>
                  </Col>
                </Row>
              </Form>
            </div>
          </Card>
          <Card className={styles.tableCard}>
            <Row style={{ marginBottom: 16 }}>
              <Authorized authority="os:plcyInfo:insert" noMatch={null}>
                <Button type="primary" onClick={this.insertOne} icon={<PlusOutlined />}>
                  新增{' '}
                </Button>
              </Authorized>
              <Authorized authority="os:plcyInfo:delete" noMatch={null}>
                <Button style={{ marginLeft: 8 }} onClick={this.deleteMany} disabled={delDis}>
                  <LegacyIcon type={del} />
                  批量删除
                </Button>
              </Authorized>
            </Row>

            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedKeys}
              loading={loading}
              data={pageData}
              columns={columns}
              rowKey="id"
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}

export default BasicList;
